#ifndef SAVE_H
#define SAVE_H

#include "qdatetime.h"
#include"singleton.hpp"
#include <QtSql/QSqlDatabase>
#include <QSqlQuery>

/*
    CREATE TABLE "main"."Untitled" (
     "message_id" INTEGER NOT NULL,
     "message" TEXT NOT NULL,
     "message_time" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
     "message_type" TEXT NOT NULL,
     PRIMARY KEY ("message_id")
    );
*/

struct Message
{
    Message() = default;
    Message(const QString& msg, const QString& type, const QDateTime& time, bool is)
        :_message(msg), _type(type), _time(time), _is_me(is)
    {}
    QString _message;
    QString _type;
    QDateTime _time;
    bool _is_me;
};

class Save:public Singleton<Save>
{
    friend class Singleton<Save>;
public:
    void ConnectSQLite();
    void Close();
    void Add(const long long message_id, const QString& chat_room, const QString& message, const QString& type, const QString &sender_user);
    void Add(const long long message_id, const QString& chat_room, const QString& message, const QString& type, const QString &sender_users, const QDateTime&);
    int QueryChatRecords(const QString& chatRoom, const long long message_id, std::vector<Message>& msg);
    bool SearchChatRecords(const QString& chatRoom, const QString& key, std::vector<Message>& msg);
    int QueryChatSum(const QString& chat_room);
    bool GetChatRoom(std::vector<QString>& list);
    QDateTime GetMaxRecord(const QString&, QString& msg);

private:
    Save();

    QSqlDatabase DB;//用于通过连接访问数据
    QSqlQuery *query;

    const QString SQLiteStructure{ R"(    CREATE TABLE "chatting_records" (
     "message_id" INTEGER NOT NULL,
     "chat_room" TEXT NOT NULL,
     "sender_user" TEXT NOT NULL,
     "message" TEXT NOT NULL,
     "message_time" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
     "message_type" TEXT NOT NULL,
     PRIMARY KEY ("message_id")
    );)"};
    const QString  InsertDataSQL{"INSERT INTO chatting_records  (message_id, chat_room, sender_user, message, message_type) VALUES (?,?, ?, ?, ?)"};
    const QString  InsertDataTimeSQL{"INSERT INTO chatting_records  (message_id, chat_room, sender_user, message, message_type, message_time) VALUES (?,?, ?, ?, ?,?)"};
    const QString QueryChatRecordsSQL{"SELECT message_id,message, message_time, message_type, sender_user FROM chatting_records WHERE ? > message_id AND chat_room = ? ORDER BY message_id DESC LIMIT 20;"};

    const QString QueryChatSumSQL{"SELECT COUNT(message_id) FROM chatting_records WHERE chat_room = ?;"};
    const QString GetMaxTimeSQL{"SELECT message_time,message FROM chatting_records WHERE chat_room=? ORDER BY message_id DESC LIMIT 1;"};
    const QString GetChatRoomSQL{"SELECT DISTINCT chat_room FROM chatting_records;"};
    const QString SearchChatRecordsSQL{"SELECT * FROM chatting_records WHERE chat_room = ? AND message LIKE ?;"};
};

#endif // SAVE_H
